//
//  CYNormalSubmitVC.m
//  CreditAddressBook
//
//  Created by Mosu&Cuu on 16/5/20.
//  Copyright © 2016年 Lee. All rights reserved.
//

#import "CYNormalSubmitVC.h"
#import "MHLoadContactController.h"
#import "UIImageView+WebCache.h"
#import "NSObject+MJKeyValue.h"
#import "CollectionViewCell.h"
#import "UIAlertView+Block.h"
#import "MBProgressHUD+LE.h"
#import "CYLoginHttpTool.h"
#import "RHAddressBook.h"
#import "CYLifePhotoVC.h"
#import "CYJsonInfo.h"
#import "CYABTool.h"
#import "CYMeTool.h"
#import "CYYDVC.h"
#import "GCD.h"
#import "CYTool.h"
#import "UIButton+WebCache.h"
#import "MWPhotoBrowser.h"
#import "LEPhotoBrowserTool.h"
#import "LEUnitView+LE.h"
#import "CYCreditTool.h"
#import "LEBarButtonItem.h"
#import "CustomIOSAlertView.h"
#import "LEImagePickerTool.h"
#import "CYDiscoveryHttpTool.h"


@interface CYNormalSubmitVC ()<UICollectionViewDataSource,UICollectionViewDelegate,MHLoadContactVCDelegate,UITextFieldDelegate>

@property(nonatomic,strong)UIView *bg;
@property(nonatomic,strong)UIView *weixinbg;
@property (weak, nonatomic) IBOutlet UIView *addressView;
@property (weak, nonatomic) IBOutlet UIView *socialView;
@property (weak, nonatomic) IBOutlet UIView *photoView;
@property (weak, nonatomic) IBOutlet UILabel *addressLab;
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;
@property (weak, nonatomic) IBOutlet UILabel *gzhLabel;
@property (weak, nonatomic) IBOutlet UITextField *qqTf;
@property (weak, nonatomic) IBOutlet UITextField *weixinTf;
@property (weak, nonatomic) IBOutlet UILabel *selectstatuesLab;
@property (weak, nonatomic) IBOutlet UIButton *selectBtn;

@property (nonatomic , strong) NSMutableArray *submitArray;
@property (nonatomic , strong) NSArray *socialArray;
@property (nonatomic , strong) NSString *namestr;
@property (nonatomic , strong) NSString *phonestr;

@property (nonatomic , strong) NSArray *dataArray1;//网络数据
@property (nonatomic , strong) NSMutableArray *dataArray2;//本地数据
@property (nonatomic , strong) NSMutableArray *dataArray;//混合数据

@property (nonatomic , strong) NSMutableArray *selectArray;//选择数据
@property (nonatomic , strong) UICollectionView *collectionView;
@property (nonatomic , strong) NSArray *cellselectArray;
@property (nonatomic , strong) UIView *shituview;
@property (nonatomic , strong) NSString *statuestr; //1需要，0不需要
@property (nonatomic , strong) NSString *realContact; //通过传50，不通过传－1
@property(nonatomic, strong) GCDTimer *GCDTimer;

@property(nonatomic, strong) GCDTimer *GCDTimer1;

@property (nonatomic, strong) UILabel *titlelab;

@property (nonatomic, strong) UIView *weixinView;

@property (nonatomic, strong) NSString *imageUrl;
@property (nonatomic, strong) NSString *weixinname;

@property (weak, nonatomic) IBOutlet UIButton *shiyitu1;
@property (weak, nonatomic) IBOutlet UIButton *shiyitu2;
@property (weak, nonatomic) IBOutlet UIView *submitView;
@property (weak, nonatomic) IBOutlet UIButton *shiyitu3;
@property (nonatomic, strong) NSMutableArray *photoUrls;
@property (nonatomic, strong) NSMutableArray *shenghuorecordArray;
@property (nonatomic, strong) NSMutableArray *shengfenzhengArray;
@property (weak, nonatomic) IBOutlet UILabel *recordLab;
@property (weak, nonatomic) IBOutlet UIView *recordView;
@property (weak, nonatomic) IBOutlet UILabel *wenxinnoticeLab;
@property (weak, nonatomic) IBOutlet UIButton *photoChooeseBtn;
@property (nonatomic, strong) NSString *urlpath2;
@property (nonatomic,strong) NSString * urlpath4;



@end

@implementation CYNormalSubmitVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.wenxinnoticeLab.text = @"温馨提示：\n1.请务必如实填写联系人的真实信息，以便客服联系审核\n2.客服将添加您的QQ及微信，请通过验证并开放空间及朋友圈";
    
    _dataArray2 = [[NSMutableArray alloc]init];
    _submitArray = [[NSMutableArray alloc]init];
    _socialArray = [[NSArray alloc]init];
    
    _photoUrls = [[NSMutableArray alloc]init];
    _shenghuorecordArray = [[NSMutableArray alloc]init];
    _shengfenzhengArray = [[NSMutableArray alloc] init];
    
    
    LEBarButtonItem *submit = [[LEBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ic_done_white_24dp"] andSelImage:nil andTitle:@"提交" target:self action:@selector(submitclick)];
    self.navigationItem.rightBarButtonItem = submit;
    
    [_shiyitu1 sd_setImageWithURL:[NSURL URLWithString:@"http://www.credit-manage.com:8058/apppic/prove/shenghuozhao1.jpg"] forState:UIControlStateNormal];
    [_shiyitu2 sd_setImageWithURL:[NSURL URLWithString:@"http://www.credit-manage.com:8058/apppic/prove/shenghuozhao2.jpg"] forState:UIControlStateNormal];
    
    
    [self setupUploadView];
    [self setimagecerIDView];
    
//    [self setshenfenzhengLoadView];
    
    
    self.title = @"基本资料";
    _qqTf.delegate = self;
    _weixinTf.delegate = self;
    
    [self localaddressarray];
    
    // Do any additional setup after loading the view from its nib.
}


//身份证正面高清图相机选择拍照
- (IBAction)shenfenzhengmianOnclick:(id)sender {
    UIImageView *shareView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"idcardz.jpg"]];
    //    CGFloat ratio = shareView.height / shareView.width;
    //    CGFloat height = CYScreeSize.height - 130;
    CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
    CGFloat w = CYScreeSize.width - 32;
    shareView.frame = CGRectMake(0, 0, w, 240);
    alertView.containerView = shareView;
    alertView.buttonTitles = @[@"知道了"];
    
    [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
        [LEImagePickerTool selectImageWithController:self edit:YES completion:^(UIImage *image) {
            [MBProgressHUD showMessage:@"处理中..." toView:self.view];
            [CYDiscoveryHttpTool uploadUserImage:image button:sender success:^(NSString *imagePath) {
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                _urlpath4 = imagePath;
                //            _cardfmLab.text = @"上传成功";
                //            _cardfmLab.textColor = CYColor(110, 214, 116, 1);
                //weakself.model.certificateNoFAddress = imagePath;
            } failure:^(NSString *message, NSError *error) {
                //            _cardfmLab.text = @"上传失败,请重新上传";
                //            _cardfmLab.textColor = [UIColor redColor];
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                if (message) {
                    //                _cardfmLab.text = @"上传失败,请重新上传";
                    //                _cardfmLab.textColor = [UIColor redColor];
                    [MBProgressHUD showError:message];
                }
            }];
        }];

    }];
    [alertView show];
}

//手持身份证高清自拍点击
- (IBAction)photochooseClick:(id)sender {
    
    UIImageView *shareView = [[UIImageView alloc] init];
    [shareView setImage:[UIImage imageNamed:@"scsfzImage"]];
    //    CGFloat ratio = shareView.height / shareView.width;
    //    CGFloat height = CYScreeSize.height - 130;
    CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
    CGFloat w = CYScreeSize.width - 32;
    shareView.frame = CGRectMake(0, 0, w, self.view.height-160);
    alertView.containerView = shareView;
    alertView.buttonTitles = @[@"知道了"];
    
    [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
        [LEImagePickerTool selectImageWithController:self edit:YES completion:^(UIImage *image) {
            [MBProgressHUD showMessage:@"处理中..." toView:self.view];
            [CYDiscoveryHttpTool uploadUserImage:image button:sender success:^(NSString *imagePath) {
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                _urlpath2 = imagePath;
                //            _cardfmLab.text = @"上传成功";
                //            _cardfmLab.textColor = CYColor(110, 214, 116, 1);
                //weakself.model.certificateNoFAddress = imagePath;
            } failure:^(NSString *message, NSError *error) {
                //            _cardfmLab.text = @"上传失败,请重新上传";
                //            _cardfmLab.textColor = [UIColor redColor];
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                if (message) {
                    //                _cardfmLab.text = @"上传失败,请重新上传";
                    //                _cardfmLab.textColor = [UIColor redColor];
                    [MBProgressHUD showError:message];
                }
            }];
        }];

    }];
    [alertView show];
    
}


- (IBAction)shiyituClick:(id)sender {
    
    UIImageView *shareView = [[UIImageView alloc] init];
    [shareView setImage:[UIImage imageNamed:@"scsfzImage"]];
    //    CGFloat ratio = shareView.height / shareView.width;
    //    CGFloat height = CYScreeSize.height - 130;
    CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
    CGFloat w = CYScreeSize.width - 32;
    shareView.frame = CGRectMake(0, 0, w, self.view.height-160);
    alertView.containerView = shareView;
    alertView.buttonTitles = @[@"知道了"];
    
    [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
    }];
    [alertView show];
    
    
}
//身份证正面高清图示意图
- (IBAction)shiyitu3Onclicked:(id)sender {
    UIImageView *shareView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"idcardz.jpg"]];
    //    CGFloat ratio = shareView.height / shareView.width;
    //    CGFloat height = CYScreeSize.height - 130;
    CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
    CGFloat w = CYScreeSize.width - 32;
    shareView.frame = CGRectMake(0, 0, w, 240);
    alertView.containerView = shareView;
    alertView.buttonTitles = @[@"知道了"];
    
    [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
    }];
    [alertView show];
}

-(void)submitclick{
    if (!_addressLab||_addressLab.text.length == 0||_addressLab.text.isEmpty) {
        CYAlertView(@"检测到您未选择通讯录联系人，请前往设置打开天下无赖对您的通讯录访问权限并选择联系人");
        return;
    }
    //    if (!_realContact||_realContact.isEmpty) {
    //        CYAlertView(@"请先通过联系人识别验证!");
    //        return;
    //    }
    
    BOOL a = [CYTool stringContainsEmoji:_addressLab.text];
    if (a) {
        //有
        CYAlertView(@"系统无法识别有表情的姓名备注，请重新选择通讯录联系人");
        return;
        
    }else{
        //没有
        
    }
    BOOL b = [CYTool stringContainsEmoji:_qqTf.text];
    if (b) {
        CYAlertView(@"请输入正确格式的微信账号");
        return;
    }else{
        
    }
    BOOL c =[CYTool stringContainsEmoji:_weixinTf.text];
    if (c) {
        CYAlertView(@"请输入正确格式的QQ账号");
        return;
    }else{
        
    }
    
    if ([self checkSuccess]) {
        
        for (int i=0; i<_photoUrls.count; i++) {
            NSDictionary *dic1 = @{@"type":@"7",@"generalPicAddress":_photoUrls[i]};
            [_submitArray addObject:dic1];
        }
        
        CYUser *user = [CYLoginHttpTool userData].user;
        
        NSString *str = nil;
        //字符串
        NSMutableString *string = [[NSMutableString alloc] init];
        str = [string JSONString];
        str = [_submitArray JSONString];
        
        
        _socialArray = @[@{@"name":_namestr,@"phone":_phonestr,@"relationShip":@"通讯录好友"}];
        NSString *str1 = nil;
        //字符串
        NSMutableString *string1 = [[NSMutableString alloc] init];
        str1 = [string1 JSONString];
        str1 = [_socialArray JSONString];
        
        UIAlertView *submit = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请务必保证所填内容真实性，如有虚假，将可能被拒贷" delegate:self cancelButtonTitle:@"修改" otherButtonTitles:@"提交", nil];
        CYLog(@"data = %@ , lingkphones = %@, qq = %@, weixin = %@",[NSString stringWithString:str],[NSString stringWithString:str1],_qqTf.text,_weixinTf.text);
        
        [submit show];
        [submit showAlertViewWithCompleteBlock:^(NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                [self countdown1];
                [CYMeTool cloudSynWithSuccess:^(id json) {
                    
                } failure:^(NSError *error) {
                } uploadProgress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
                }];
                
                CYLog(@"str = %@",str);
                
                [MBProgressHUD showMessage:nil toView:self.view];
                NSArray *contactsArr = [CYMeTool contactsArr];
                NSInteger count = contactsArr.count;
                [CYHttpTool postWithURL:[CYURL shared].saveGeneralInfoAuto params:@{@"userId":user.userId,@"token":user.token,@"data":[NSString stringWithString:str],@"linkPhones":[NSString stringWithString:str1],@"qq":_weixinTf.text,@"weiXin":_qqTf.text,@"contactCount":@(count),@"realContact":@"50",@"certificateNoAddress":_urlpath2,@"certificateNoZAddress":_urlpath4,}  success:^(id json) {
                    [MBProgressHUD hideHUDForView:self.view];
                    CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
                    if (jsonInfo.isSuccess) {
                        [MBProgressHUD showSuccess:jsonInfo.message];
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"CYGenealNotification" object:nil userInfo:nil];
                        [self.navigationController popViewControllerAnimated:YES];
                    }else{
                        [MBProgressHUD showError:jsonInfo.message];
                    }
                } failure:^(NSError *error) {
                    [MBProgressHUD hideHUDForView:self.view];
                    CYAlertView(@"网络错误!");
                }];
            }
        }];
    }
}


- (void)setimagecerIDView{
    // image 前缀
    NSString *preFixString = @"http://image.credit-manage.com/";
    // 屏幕的宽度 (也是承载imageView的view的宽度)
    CGFloat screenWidth = [[UIScreen mainScreen] bounds].size.width;
    // image各个边界的间隔
    CGFloat space = 10.f;
    // imageview的width (设定为5张)
    CGFloat imgWidth = (screenWidth - space * 6 ) / 5;
    // imageview的height
    CGFloat imgHeight = _recordView.frame.size.height - space * 2;
    // 由于是xib + 手码, 代码获取xib控件的frame 必须在主线程中获取
    dispatch_async(dispatch_get_main_queue(), ^{
        CYUser *user = [CYLoginHttpTool userData].user;
        [CYHttpTool postWithURL:[CYURL shared].getGeneralInfoPics params:@{@"userId":user.userId,@"token":user.token} success:^(id json) {
            //        CYLog(@"json = %@",json);
            CYJsonInfo *jsoninf = [CYJsonInfo objectWithKeyValues:json];
            NSMutableArray *data = jsoninf.data;
            for (NSDictionary *dic in data) {
                // 取网络	图片地址
                NSString *provePicAddress = [dic objectForKey:@"generalPicAddress"];
                if (![provePicAddress isKindOfClass:[NSNull class]]) {
                    [_shenghuorecordArray addObject:provePicAddress];
                    
                }
                CYLog(@"address = %@",_shenghuorecordArray);
                for (int i = 0; i < _shenghuorecordArray.count; i++ ) {
                    // image的url string
                    NSString *imgUrlString = [_shenghuorecordArray objectAtIndex:i];
                    imgUrlString = [preFixString stringByAppendingString:imgUrlString];
                    
                    
                    // 创建imageView
                    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(space + (imgWidth + space) * i, space, imgWidth, imgHeight)];
                    imgView.backgroundColor = [UIColor whiteColor];
                    // 此处你可使用SDWebImage来加载
                    [imgView sd_setImageWithURL:[NSURL URLWithString:imgUrlString]];
                    [_recordView addSubview:imgView];
                }
                if (_shenghuorecordArray.count){
                    _recordLab.hidden = YES;
                    UITapGestureRecognizer *tag = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(photoBrowser:)];
                    [_recordView addGestureRecognizer:tag];
                }
            }
        } failure:^(NSError *error) {
            
        }];
    });
}

/**
 *  图片浏览器
 */
- (void)photoBrowser:(UITapGestureRecognizer *)tag {
    NSArray *urls = _shenghuorecordArray;
    MWPhoto *photo = nil;
    NSMutableArray *photos = [NSMutableArray array];
    for (NSString *url in urls) {
        photo = [MWPhoto photoWithURL:CYURLWithService(url)];
        //        photo.caption = @"title";
        [photos addObject:photo];
    }
    [LEPhotoBrowserTool showPhotoBrowserWithController:self photos:photos];
}

- (void)setupUploadView {
    //生活照
    [LEUnitView imageScrollView:self.submitView controller:self block:^(LEUnitView *unitView, LEUnitCell *cell, UIImage *image) {
        [CYCreditTool uploadPicImage:image success:^(NSString *imageUrl) {
            [_photoUrls addObject:imageUrl];
            cell.ratio = 1;
        } failure:^(NSError *error) {
            //删除
            [unitView deleteLastCell];
        } uploadProgress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
            CGFloat a = totalBytesWritten;
            CGFloat b = totalBytesExpectedToWrite;
            cell.ratio = a/b - .01;
        }];
    } cellClick:^(LEUnitView *unitView, LEUnitCell *cell) {
    }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //主要是[receiver resignFirstResponder]在哪调用就能把receiver对应的键盘往下收
    
    [_qqTf resignFirstResponder];
    [_weixinTf resignFirstResponder];
    return YES;
}

//本地联系人数据处理
- (void)localaddressarray{
    //     RHAddressBook *ab = [CYABTool addressBook];
    NSArray *contactsArr = [CYMeTool contactsArr];
    if (contactsArr.count) {
        //去除字典中的headerImage
        NSMutableArray *newContactsArr = [NSMutableArray array];
        for (NSDictionary *dic in contactsArr) {
            if (dic[@"headerImage"]) {
                NSMutableDictionary *dicMu = [NSMutableDictionary dictionaryWithDictionary:dic];
                [dicMu removeObjectForKey:@"headerImage"];
                
                [newContactsArr addObject:dicMu];
            } else {
                [newContactsArr addObject:dic];
            }
        }
        NSMutableSet *randomSet = [[NSMutableSet alloc] init];
        while ([randomSet count] < 6) {
            int r = arc4random() % [newContactsArr count];
            [randomSet addObject:[newContactsArr objectAtIndex:r]];
        }
        NSArray *randomArray = [randomSet allObjects];
        NSLog(@"%@",randomArray);
        for (NSMutableDictionary *dic in randomArray) {
            NSString *str = [dic objectForKey:@"name"];
            [_dataArray2 addObject:str];
        }
    }
}

- (IBAction)addresschooseClick:(id)sender {
    
    MHLoadContactController *vc = [MHLoadContactController new];
    vc.delegate = self;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - MHLoadContactVCDelegate
- (void)loadContactDidSelectContactName:(NSString *)contactName telNumberArray:(NSArray *)telNumberArray
{
    _namestr = contactName;
    _phonestr = telNumberArray[0];
    _addressLab.text = [NSString stringWithFormat:@"%@ %@",contactName,telNumberArray[0]];
}


- (IBAction)addressyanzhengClick:(id)sender {
    CYUser *user = [CYLoginHttpTool userData].user;
    [MBProgressHUD showMessage:@"获取中..." toView:self.view];
    [CYHttpTool postWithURL:[CYURL shared].getRandomLinkPhone params:@{@"userId":user.userId} success:^(id json) {
        [MBProgressHUD hideHUDForView:self.view];
        CYJsonInfo *jsoninfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsoninfo.isSuccess) {
            [MBProgressHUD hideHUDForView:self.view];
            _selectArray = [[NSMutableArray alloc]init];
            _dataArray = [[NSMutableArray alloc]init];
            for (int i = 0; i<6; i++) {
                [_dataArray addObject:_dataArray2[i]];
            }
            NSArray *arr = jsoninfo.data;
            NSMutableArray *array = [[NSMutableArray alloc]init];
            for (NSDictionary *dic in arr) {
                NSString *namestr = [dic objectForKey:@"name"];
                [array addObject:namestr];
                
            }
            //            NSArray *array = [[NSArray alloc] initWithObjects:@"A",@"B",@"C",@"D",@"E",@"1",@"3",@"2",nil];
            NSMutableSet *randomSet = [[NSMutableSet alloc] init];
            while ([randomSet count] < 3) {
                int r = arc4random() % [array count];
                [randomSet addObject:[array objectAtIndex:r]];
            }
            NSArray *randomArray = [randomSet allObjects];
            NSLog(@"%@",randomArray);
            
            for (int i = 0;i<3;i++){
                [_dataArray addObject:randomArray[i]];
                //                [_collectionView reloadData];
            }
            
            for(int i = 0; i< _dataArray.count; i++)
            {
                
                int m = (arc4random() % (_dataArray.count - i)) + i;
                [_dataArray exchangeObjectAtIndex:i withObjectAtIndex: m];
            }
            [self countdown:sender];
            [self createCollectionView];
        }
        
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
    }];
    
}
- (void)countdown:(UICollectionView *)view {
    self.GCDTimer = [[GCDTimer alloc] initInQueue:[GCDQueue mainQueue]];
    
    CYWeakObject(weakself, self);
    __block int time = 20;
    [self.GCDTimer event:^{
        if (time < 1) {
            //设置界面的按钮显示 根据自己需求设置
            _bg.hidden = YES;
            _shituview.hidden = YES;
            [weakself.GCDTimer destroy];
        } else {
            //        NSLog(@"time:%d", time);
            _titlelab.text = [NSString stringWithFormat:@"请选择通讯录内您认识的姓名\n剩余:%d秒",time];
            
            //            btn.backgroundColor = CYColor(211, 211, 211, 1);
        }
        time--;
    } timeInterval:NSEC_PER_SEC * 1];
    [self.GCDTimer start];
}

- (void)countdown1 {
    self.GCDTimer = [[GCDTimer alloc] initInQueue:[GCDQueue mainQueue]];
    __block int time = 3;
    [self.GCDTimer event:^{
        if (time < 1) {
            [self.navigationController popViewControllerAnimated:YES];
            
        } else {
        }
        time--;
    } timeInterval:NSEC_PER_SEC * 1];
    [self.GCDTimer start];
}


-(void)createCollectionView
{
    UIView *bgView = [[UIView alloc] initWithFrame:self.view.frame];
    bgView.backgroundColor = [UIColor grayColor];
    bgView.alpha = 0.8;
    self.bg = bgView;
    self.bg.hidden = NO;
    [[UIApplication sharedApplication].keyWindow addSubview:bgView];
    //     _shituview =[[UIView alloc]initWithFrame: CGRectMake(30,120,self.view.frame.size.width-60,400)];
    _shituview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.size.width-100, self.view.height/1.8)];
    _shituview.layer.cornerRadius = 5.0f;
    _shituview.center = self.view.center;
    _shituview.backgroundColor = [UIColor whiteColor];
    [[UIApplication sharedApplication].keyWindow addSubview:_shituview];
    [[UIApplication sharedApplication].keyWindow bringSubviewToFront:_shituview];
    
    UILabel *titlelab = [[UILabel alloc]init];
    _titlelab = titlelab;
    titlelab.numberOfLines = 2;
    titlelab.frame = CGRectMake(2, 2, _shituview.frame.size.width-4, 50);
    titlelab.backgroundColor = [UIColor whiteColor];
    titlelab.text  = @"请选择6个您认识的名字";
    titlelab.textAlignment = NSTextAlignmentCenter;
    titlelab.textColor = [UIColor grayColor];
    titlelab.font = [UIFont systemFontOfSize:12.0f];
    [_shituview addSubview:titlelab];
    
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    //     _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(30, 60, _shituview.frame.size.width-60, 250) collectionViewLayout:layout];
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(10, _titlelab.y+_titlelab.height+10,_shituview.width-20, _shituview.height/1.2 ) collectionViewLayout:layout];
    //    _collectionView.center = CGPointMake(_shituview.width/2,_shituview.height/2);
    _collectionView.backgroundColor = [UIColor whiteColor];
    [_collectionView registerNib:[UINib nibWithNibName:@"CollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"CollectionViewCell"];
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.alwaysBounceVertical = YES;
    
    UIButton *quxiaoBtn = [[UIButton alloc]initWithFrame:CGRectMake(5, 5, 20,20)];
    quxiaoBtn.layer.cornerRadius = 5.0f;
    [quxiaoBtn setImage:[UIImage imageNamed:@"icon_close_theme"] forState:UIControlStateNormal];
    [quxiaoBtn setTitle:@"取消" forState:UIControlStateNormal];
    [quxiaoBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [quxiaoBtn addTarget:self action:@selector(cancleclick) forControlEvents:UIControlEventTouchUpInside];
    
    [_shituview addSubview:quxiaoBtn];
    [_shituview addSubview:_collectionView];
}

-(void)cancleclick{
    [_bg removeFromSuperview];
    [_shituview removeFromSuperview];
    
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionViewCell" forIndexPath:indexPath];
    cell.layer.cornerRadius = 3.0f;
    
    cell.nameLab.text = _dataArray[indexPath.row];
    //    NSLog(@"cell.name = %@",_cell.nameLab.text);
    if (_selectArray.count ==0) {
        cell.cellSelected = NO;
        [cell setBackgroundColor:CYColor(239, 239, 244, 1)];
        
    }
    return cell;
    
}

#pragma  mark --返回item的数目
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 9;
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
#pragma mark --cell的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    return CGSizeMake(_collectionView.width/3.2 ,_collectionView.width/3);
}
#pragma mark -- 选中的事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    CollectionViewCell *cell = (CollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    [cell setBackgroundColor:CYColor(110, 239, 117, 1)];
    _cellselectArray = [self.collectionView indexPathsForSelectedItems];
    if (cell.cellSelected) {
        CYAlertView(@"请勿重复选择");
        
    }else{
        cell.cellSelected = YES;
        [_selectArray addObject:_dataArray[indexPath.row]];
        NSLog(@"选中%ld",(long)indexPath.row);
        if (_selectArray.count == 6){
            [self judgmentData];
            [_selectArray removeAllObjects];
            [collectionView reloadData];
            
        }
    }
    
}
-(void)judgmentData
{
    int i = 0;
    for(NSString *select in _selectArray){
        for (NSString *string in _dataArray2){
            if ([select isEqualToString:string]){
                i++;
            }
        }
    }
    NSLog(@"%d",i);
    if (i >=4){
        NSLog(@"超过80％");
        _realContact = @"50";
        _selectBtn.hidden = YES;
        _selectstatuesLab.text = @"您已验证完成!";
        _bg.hidden = YES;
        [_shituview removeFromSuperview];
        CYAlertView(@"验证完成!");
        return;
        
    }else {
        NSLog(@"没有80％");
        _realContact = @"-1";
        _selectstatuesLab.text = @"您已验证完成!";
        _selectBtn.hidden = YES;
        [_selectArray removeAllObjects];
        _bg.hidden = YES;
        [_shituview removeFromSuperview];
        CYAlertView(@"验证完成");
        return;
    }
}

- (IBAction)shiyitu1Click:(id)sender {
    
    UIImageView *shareView = [[UIImageView alloc] init];
    [shareView sd_setImageWithURL:[NSURL URLWithString:@"http://www.credit-manage.com:8058/apppic/prove/shenghuozhao1.jpg"]];
    //    CGFloat ratio = shareView.height / shareView.width;
    //    CGFloat height = CYScreeSize.height - 130;
    CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
    CGFloat w = CYScreeSize.width - 32;
    shareView.frame = CGRectMake(0, 0, w, self.view.height-160);
    alertView.containerView = shareView;
    alertView.buttonTitles = @[@"知道了"];
    
    [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
    }];
    [alertView show];
    
    
}
- (IBAction)shiyitu2Click:(id)sender {
    UIImageView *shareView = [[UIImageView alloc] init];
    [shareView sd_setImageWithURL:[NSURL URLWithString:@"http://www.credit-manage.com:8058/apppic/prove/shenghuozhao2.jpg"]];
    //    CGFloat ratio = shareView.height / shareView.width;
    //    CGFloat height = CYScreeSize.height - 130;
    CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
    CGFloat w = CYScreeSize.width - 32;
    shareView.frame = CGRectMake(0, 0, w, self.view.height-160);
    alertView.containerView = shareView;
    alertView.buttonTitles = @[@"知道了"];
    
    [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
    }];
    [alertView show];
    
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 1;
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 7;
}


-(void)viewbeclose{
    _weixinbg.hidden = YES;
    _weixinView.hidden = YES;
    
}
//公众号复制按钮
- (IBAction)gzhfzBtnOnclicked:(UIButton *)sender {
    _weixinname = _gzhLabel.text;
    UIPasteboard *pab = [UIPasteboard generalPasteboard];
    [pab setString:_weixinname];
    if (pab == nil) {
        [MBProgressHUD showError:@"复制失败"];
        
    }else
    {
        [MBProgressHUD showSuccess:@"已复制"];
        
    }
    
}

- (IBAction)photoClick:(id)sender {
    CYLifePhotoVC *photoselectVC = [[CYLifePhotoVC alloc]init];
    [self.navigationController pushViewController:photoselectVC animated:YES];
    
}

- (BOOL)checkSuccess {
    
    if (!_qqTf||_qqTf.text.length==0||!_urlpath2||!_weixinTf||_weixinTf.text.length==0||!_photoUrls||_photoUrls.count<3) {
//
        CYAlertView(@"请按照要求填写全信息!");
        return NO;
    }
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
